/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License Version
 *  3 as published by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307,
 *  USA.
 */

#include "tcpserver.h"
#include <Core/logger/logger.h>
#include <tasks/servertask.h>
#include <optraapplication.h>
#include <tasks.h>

namespace Optra { namespace Server {

class TcpServerPrivate{
public:
    TcpServerPrivate(){}
    ~TcpServerPrivate(){}
    bool disabled;
    int port;
};

TcpServer::TcpServer(QObject *parent) :
    QTcpServer(parent), O_PRIVATE_CREATE(TcpServer)
{
    LI.Info() << "TcpServer initialize";

    O_D(TcpServer);
    d->disabled = !OptraConfigValue("TcpServer", "enabled", false).toBool();
    d->port = OptraConfigValue("TcpServer", "port", 51999).toInt();

    LI.Debug() << "Config:";
    LI.Debug() << "disabled:" << d->disabled;
    LI.Debug() << "port:" << d->port;
}

TcpServer::~TcpServer()
{ 
    O_PRIVATE_DELETE;
}

void TcpServer::start()
{
    O_D(TcpServer);
    if (!d->disabled){
        if (listen(QHostAddress::LocalHost, d->port))
        {
            LI.Info() << QString("TcpServer Start on host:%1 ,port:%2").arg(serverAddress().toString()).arg(serverPort());
        }
        else{
            LI.Error() << "TcpServer unable to start:" << errorString();
        }
    }else{
        LI.Info() << "Tcp Server is disabled. you can enable it by set section \"server {enabled:true}\" in config file";
    }


}

void TcpServer::incomingConnection(qintptr socketDescriptor)
{
    LI.Debug() << "Incomming Connection " << socketDescriptor;
    ServerTask* task = new ServerTask(socketDescriptor);
    using ::Optra::OptraApplication;
    OptraApplication::Instance()->tasks()->start(task, tr("TCP Server connection"));
}

}}
